package com.itheima.Test;

import com.itheima.domain.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.InputStream;
import java.security.PublicKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Demo1 {
    private SqlSession session = null;
    private InputStream is = null;
    @Before
    public void before() throws Exception {
        //1、读取核心配置文件
        is = Resources.getResourceAsStream("sql.xml");
        //2、构建SqlSessionFactory对象
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
        //3、获取SqlSession对象
        session = factory.openSession();
    }
    @After
    public void after() throws Exception {
        //5、事务提交
        session.commit();
        //6、释放资源
        session.close();
        is.close();
    }

    //    根据id查询信息
    @Test
    public void findById() {
        User user = session.selectOne("one.findById", 1);
        System.out.println(user);
    }

    //    查询所有人信息
    @Test
    public void findAll() {
        List<User> list = session.selectList("one.findAll");
        System.out.println(list);
    }

    // 查询所有人个数
    @Test
    public void findCount() {
        int num = session.selectOne("one.findCount");
        System.out.println(num);
    }

    // 统计男女的人数
    @Test
    public void findSexCount() {
        List<Map> map = session.selectList("one.findSexCount");
        System.out.println(map);


    }

        // 根据id更新用户信
    @Test
    public void updateById() {
        User user = session.selectOne("one.findById", 1);
        user.setUsername("lirui");
        session.update("one.updateById", user);
    }
    // 根据邮箱密码查询
    @Test
    public void findByEm(){
        HashMap hm = new HashMap();
        hm.put("email","22");
        hm.put("password","123");
        User user = session.selectOne("one.findByEm", hm);
        System.out.println(user);
    }


    @Test
    public  void findName(){
        List<User> list = session.selectList("one.findName", "%li%");
        System.out.println(list);
    }
    @Test
    public void inert(){
        //封装user数据
        User user=new User();
        user.setUsername("西施2");
        user.setSex("女");
        user.setAge(31);
        user.setPassword("123456");
        user.setEmail("666@qq.com");
        System.out.println("执行保存前："+user);
        session.insert("one.saveUser",user);
        System.out.println("执行保存后："+user);

    }
}
